<?php
class Opinion extends MY_Front_Controller {

	function __construct() {
		parent::__construct();
		$this->load->model('opinion_model');
	}
	
	public function index(){
		$data = array();
		
		$data['opinions'] = $this->opinion_model->getOpinion(array('language_id' => $this->config->item('lang_obj')->id))->result();

		$this->template->add_js('application/assets/js/jqueryPlugins/jquery.pajinate.min.js');
		$this->template->add_js('application/assets/js/opinions.js');
		
		$this->template->write_view('content','front/opinions.php',$data);
		$this->template->write_view ( 'footer', 'templates/front/footer.php', array('hide_opinion' => 1) ,true);
		$this->template->render();
	}
	
	function get_opinion($id = 0){
		if ($id){
			$question = $this->questions_model->get_by_id($id);
			$question->views++;
			
			$html = '<div>' . lang('asked_by') . ' ' . (isset($question->user_name) ? $question->user_name : lang('anonimus')) . '</div>';
			$html .= '<div>' . $question->question . '</div>';
			
			if ($question->answered_by){
				$html .= '<div>' . lang('answered_by') . ' ' . (isset($question->answered_by_user) ? $question->answered_by_user : lang('anonimus')) . '</div>';
				$html .= '<div>' . $question->answer . '</div>';
			}
	
			$question->update();
			
			echo json_encode(array('status' => 1, 'html' => $html));
		} else {
			echo json_encode(array('status' => 0));
		}
	}
	
	function save_opinion(){
		$this->load->model('product_model');
		$product_id = $_REQUEST['product_id'];
		$opinion = $_REQUEST['opinion'];
		$user = $this->session->userdata('user');
		$product = $this->product_model->get_by_id($product_id);
		if($product_id && !empty($product_id) && $opinion && !empty($opinion)){
			$this->opinion_model->fields['user_id']    = $user['id'];
			$this->opinion_model->fields['product_id'] = $product_id;
			$this->opinion_model->fields['date']    = date('Y-m-d H:i:s');
			$this->opinion_model->fields['opinion'] = $opinion;
			$this->opinion_model->fields['language_id'] = $product->language_id;
			
			$opinions = $this->opinion_model->fields_to_object();
			$opinion_id = $opinions->insert();
			if ($opinion_id){
				echo json_encode(array('status' => 1, 'msg' => lang('success')));
			}else {
				echo json_encode(array('status' => 0 , 'msg' => lang('error_to_save')));
			}
		} else {
			echo json_encode(array('status' => 0, "msg" => lang('param_error')));
		}
	}
}